package cn.kgm.bio.chat.server;

import cn.kgm.bio.chat.common.Constants;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Set;

/**
 * @Author: Kappi
 * @Date: 2023-3-1 11:35
 * @ClassName: ServerReader
 * @Description: cn.kgm.bio.chat.server ServerReader
 * @Version 1.8
 */
public class ServerReader extends Thread {

    Socket socket;

    ServerReader(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(this.socket.getInputStream());
            while (true) {
                int flag = dis.readInt();
                if (flag == 1) {
                    String name = dis.readUTF();
                    System.out.println(name + "-->" + socket.getRemoteSocketAddress());
                    ServerChat.onLineSocket.put(this.socket, name);
                }
                writeMsg(flag, dis);
            }
        } catch (Exception e) {
            System.out.println(ServerChat.onLineSocket.get(socket) + " : 下线了~");
            try {
                writeMsg(1, dis);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    private void writeMsg(int flag, DataInputStream dis) throws IOException {
        String msg = null;
        if (flag == 1) {
            StringBuilder sb = new StringBuilder();
            Collection<String> onlineUsers = ServerChat.onLineSocket.values();
            if (onlineUsers.size() > 0) {
                onlineUsers.forEach(name -> {
                    sb.append(name).append(Constants.SPILIT);
                });
                msg = sb.substring(0, sb.lastIndexOf(Constants.SPILIT));
                sendMsgToAll(flag, msg);
            }
        } else if (flag == 2 || flag == 3) {
            String newMsg = dis.readUTF();
            String sendName = ServerChat.onLineSocket.get(socket);
            StringBuilder msgFinal = new StringBuilder();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (flag == 2) {
                msgFinal.append(sendName).append(" ")
                        .append(sdf.format(System.currentTimeMillis()))
                        .append("\r\n");
                msgFinal.append(" ")
                        .append(newMsg)
                        .append("\r\n");
                sendMsgToAll(flag, String.valueOf(msgFinal));
            } else {
                msgFinal.append(sendName).append(" ")
                        .append(sdf.format(System.currentTimeMillis()))
                        .append("对您单发: ")
                        .append("\r\n");
                msgFinal.append(" ")
                        .append(newMsg)
                        .append("\r\n");
                sendMsgToOne(socket, String.valueOf(msgFinal));
            }

        }
    }

    private void sendMsgToAll(int flag, String msg) {
        Set<Socket> sockets = ServerChat.onLineSocket.keySet();
        sockets.forEach(socket -> {
            DataOutputStream dos = null;
            try {
                dos = new DataOutputStream(socket.getOutputStream());
                dos.writeInt(flag);
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private void sendMsgToOne(Socket socket, String msg) {
        try {
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            dos.writeInt(2);
            dos.writeUTF(msg);
            dos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
